﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QFlow.Data;
using System.Data.Common;
using System.Linq;


namespace QFlow.Windows.Forms
{
    public partial class NewProduct : QFlow.Utils.BaseForm
    {
        bool _New;
        ProductType _ProductType;
        int _ProductId;

        public NewProduct(ProductType productType, bool dialog, QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();

            if (productType == ProductType.Stockable)
                this.pnlStockable.Visible = true;

            this._ProductType = productType;
            _New = true;
            btnCancel.Visible = dialog;
        }

        public NewProduct(ProductType productType, int productId, QFlowDbContext context)
            : base(context)
        {
            InitializeComponent();
            //----------------------------------
            if (productType == ProductType.Stockable)
                this.pnlStockable.Visible = true;

            _ProductId = productId;
            _New = false;
            btnCancel.Visible = true;
            this._ProductType = productType;
            this.Text = QFlow.Windows.Properties.Resources.FRMEditProduct;
        }

        private void NewProduct_Load(object sender, EventArgs e)
        {
            FillCategories();
            FillBrands();
            FillUnits();
            if (!_New)
            {
                if (_ProductType == ProductType.Stockable)
                {
                    StockableProduct product = this.Context.StockableProducts.Single(p => p.ProductID == _ProductId);
                    lblID.Text = _ProductId.ToString();
                    txtName.Text = product.Product.Name;
                    txtNotes.Text = product.Product.Notes;
                    txtDescription.Text = product.Product.Description;
                    cmbBrand.SelectedValue = product.Product.BrandID;
                    cmbCategory.SelectedValue = product.Product.CategoryID;

                    txtGlobalBarcode.Text = product.GlobalBarcode;
                    txtBarcode.Text = product.Barcode;
                    txtSalesPrice.Text = product.SalesUnitPrice.ToString("F");
                    txtPurchasePrice.Text = product.PurchaseUnitPrice.ToString("F");
                    txtTaxesPercent.Text = product.TaxesPercent.ToString("F");
                    txtReorderPoint.Text = product.ReorderPoint.ToString("F");
                    if (product.ReorderQuantity.HasValue)
                        txtReorderQuantity.Text = product.ReorderQuantity.Value.ToString("F");
                    cmbUnits.SelectedValue = product.UnitID;
                }
                else
                {
                    Product product = this.Context.Products.Single(p => p.ProductID == _ProductId);
                    lblID.Text = _ProductId.ToString();
                    txtName.Text = product.Name;
                    txtNotes.Text = product.Notes;
                    txtDescription.Text = product.Description;
                    cmbBrand.SelectedValue = product.BrandID;
                    cmbCategory.SelectedValue = product.CategoryID;
                }
            }
        }

        private void FillBasicProduct(Product product)
        {
            product.Name = this.txtName.Text;
            product.BrandID = (int)this.cmbBrand.SelectedValue;
            product.CategoryID = (int)this.cmbCategory.SelectedValue;
            if (!string.IsNullOrEmpty(txtDescription.Text))
                product.Description = this.txtDescription.Text;

            if (!string.IsNullOrEmpty(txtNotes.Text))
                product.Notes = this.txtNotes.Text;

            product.IsNonStockable = (_ProductType == ProductType.NonStockable || _ProductType == ProductType.Service);
            product.IsService = (_ProductType == ProductType.Service);
        }

        private void FillStockableProduct(StockableProduct product)
        {
            if (_New)
            {
                product.Barcode = this.Context.StockableProducts.GetBarcode();
                product.CurrentQuantity = 0;
            }
            product.GlobalBarcode = this.txtGlobalBarcode.Text;
            product.SalesUnitPrice = double.Parse(txtSalesPrice.Text);
            product.PurchaseUnitPrice = double.Parse(txtPurchasePrice.Text);
            product.TaxesPercent = double.Parse(txtTaxesPercent.Text);
            product.ReorderPoint = double.Parse(txtReorderPoint.Text);
            product.UnitID = (int)this.cmbUnits.SelectedValue;
            if (!string.IsNullOrEmpty(txtReorderQuantity.Text))
                product.ReorderQuantity = double.Parse(txtReorderQuantity.Text);

        }

        private void FillCategories()
        {
            this.cmbCategory.DataSource = this.Context.ProductCategories.ToArray();
        }

        private void FillBrands()
        {
            this.cmbBrand.DataSource = this.Context.ProductBrands.ToArray();

        }

        private void FillUnits()
        {
            this.cmbUnits.DataSource = this.Context.ProductUnits.ToArray();
        }

        private void NewProduct_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (txtName.CausesValidation)
            {
                txtName.CausesValidation = false;
                cmbBrand.CausesValidation = false;
                cmbCategory.CausesValidation = false;

                txtSalesPrice.CausesValidation = false;
                cmbUnits.CausesValidation = false;
                txtReorderPoint.CausesValidation = false;
                this.Close();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (this._ProductType != ProductType.Stockable)
                {
                    if (this.vldbasic.Validate())
                    {
                        if (_New)
                        {
                            Product product = new Product();
                            FillBasicProduct(product);
                            this.Context.Products.InsertOnSubmit(product);
                            this.Context.SubmitChanges();
                        }
                        else
                        {
                            Product product = this.Context.Products.Single(p => p.ProductID == _ProductId);
                            FillBasicProduct(product);
                        }
                        PostSave();
                    }
                }
                else
                {
                    if (this.vldbasic.Validate() && this.vldStock.Validate())
                    {
                        if (_New)
                        {
                            Product product = new Product();
                            FillBasicProduct(product);

                            product.StockableProduct = new StockableProduct();
                            FillStockableProduct(product.StockableProduct);

                            this.Context.Products.InsertOnSubmit(product);
                            this.Context.SubmitChanges();
                        }
                        else
                        {
                            Product product = this.Context.Products.Single(p => p.ProductID == _ProductId);
                            FillBasicProduct(product);
                            FillStockableProduct(product.StockableProduct);
                            this.Context.SubmitChanges();
                        }
                        PostSave();
                    }
                }
            }
            catch
            {
                MessageBox.Show(QFlow.Windows.Properties.Resources.MBCantSaveChanges, QFlow.Windows.Properties.Resources.MBErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        private void PostSave()
        {
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtGlobalBarcode_Validating(object sender, CancelEventArgs e)
        {
            if (_New)
            {
                if (!string.IsNullOrEmpty(txtGlobalBarcode.Text))
                {
                    if (!this.Context.StockableProducts.CheckNewGlobalBarcode(txtGlobalBarcode.Text))
                    {
                        highlighter2.SetHighlightColor(txtGlobalBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.Red);
                        errorProvider2.SetError(txtGlobalBarcode, QFlow.Windows.Properties.Resources.EPGlobalBarcodeUsed);
                        e.Cancel = true;
                        return;
                    }
                }
                highlighter2.SetHighlightColor(txtGlobalBarcode, DevComponents.DotNetBar.Validator.eHighlightColor.None);
                errorProvider2.Clear();
                e.Cancel = false;
            }
        }
    }
}
